<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>socket.io</title>
  <style>
    #app {
      width: 400px;
    }

    #ul {
      width: 100%;
      padding: 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
    }

    #ul li {
      width: 75%;
      list-style: none;
      border-radius: 10px;
      border: 1px solid #ccc;
      background-color: #f9f9f9;
      padding: 5px 12px;
      margin: 6px;
    }

    #ul li p {
      margin: 0;
    }

    .self {
      align-self: flex-end;
      color: coral;
      text-align: right;
    }

    .other {
      color: darkslategray;
    }

    #input {
      border-radius: 10px;
      width: 200px;
      font-size: 20px;
      height: 32px;
      line-height: 32px;
    }

    #btn {
      width: 100px;
      height: 32px;
      border: none;
      font-size: 20px;
    }
  </style>
</head>

<body>
  <div id="app">
    <div v-if="isLink">
      <ul id="ul">
        <li :class="[li.from=='self'? 'self' : 'other']" v-for="li in list">
          <p>
            {{li.value}}
          </p>
        </li>
      </ul>
      <input id="input" type="text" v-model="inputText"></textarea>
      <input id="btn" type="button" value="send" @click="send">
    </div>
    <div v-else>
      网络没有连接
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script type="text/javascript" src="http://localhost:8899/socket.io/socket.io.js"></script>
  <script type="text/javascript">
    let socket = io('ws://localhost:8899')

    var app = new Vue({
      el: '#app',
      data: {
        inputText: '',
        list: [],
        isLink: false
      },
      methods: {
        send() {
          if (!this.inputText) return;
          socket.emit('send', this.inputText);
          this.list.push({
            value: this.inputText,
            from: 'self'
          })

          this.inputText = '';
        }
      }
    })
    socket.on('send', str => {
      app.list.push({
        value: str,
        from: 'other'
      })
    })
    socket.on('connect', () => {
      console.log("已连接");
      app.isLink = true;
    })
    socket.on('disconnect', () => {
      console.log('断开连接');
      app.isLink = false;
    })
  </script>
</body>

</html>
